<template>
  <el-input
      v-model="query"
      placeholder="Please enter keyword"/>

  <el-tree :data="tableData"
           :props="props"
           ref="treeRef"
           @node-click="handleNodeClick"
           draggable
           node-key="id"
           :accordion="true"
           :row-class-name="rowClassName"
           @check-change="handleCheckChange"
           :highlight-current="true"
           default-expand-all
           :filter-node-method="filterNode"
           :expand-on-click-node="false"
           :height="750"
           show-checkbox
           icon="a"
           id="tree">

    <template #default="{ node, data }">
      <div class="tree_operation">
      <span class="custom-tree-node">
        <!-- 自定义展开图标 -->

        <span class="tree-icon" @click.stop="toggleExpand(data,node)">
          <template v-if="!data.hasOwnProperty('caseid')">
              <el-icon v-if="node.expanded" :size="15"><CaretBottom /></el-icon>
                <el-icon v-else :size="15"><CaretRight /></el-icon>
          </template>

        </span>
        <template v-if="!data.hasOwnProperty('caseid')">
          <el-icon><Collection /></el-icon>
          <span class="active-node" v-if="cur_data.id==data.id">{{ node.label }}</span>
          <span v-else>{{ node.label }}</span>
        </template>
        <template v-else>
            <div class="testcase">
              <el-icon><Document /></el-icon>
              <span class="active-node" v-if="cur_data.id==data.id">{{ node.label }}</span>
              <span v-else>{{ node.label }}</span>
            </div>

        </template>
      </span>
      </div>
    </template>
  </el-tree>
  <el-button type="success" plain @click="SyncCases" >确认</el-button>
</template>


<script setup lang="ts">
import {onMounted, reactive, ref,watch} from "vue"
import Node from "element-plus/es/components/tree/src/model/node"
const prop = defineProps(["tool", "meau" ])
const emit = defineEmits(["ChangeFather"])
import type { TreeInstance } from 'element-plus'
const cur_data = ref({
  name:null,
  id:null,
  data:null,
  childs:[]
})
const cur_node = ref(Node)
const query = ref('')
const meau = prop.meau
const tableData = ref([])
const currentKey = ref(null)
var testcases = [] //用例
const treeRef = ref<TreeInstance>()
watch(query, (val) => {
  treeRef.value!.filter(val)
})
interface Tree {
  id: number
  name: string
  caseid:string
  child?: Tree[]
}
const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.name.includes(value)
}

const handleCheckChange = (
    data: Tree,
    checked: boolean,//选中时未true,取消时为false
    indeterminate: boolean
) => {
  if (checked == false) {
    return
  }
  if (data.hasOwnProperty("caseid")){
    testcases.push({
      id:data.id,
      caseid:data.caseid,
      name:data.name,
    })
  }
}

const SyncCases=async ()=> {
  if (testcases.length == 0) {
    return
  }
  emit("ChangeFather", testcases);
  resetChecked()
  await testcases.splice(0)
}
const resetChecked = () => {
  treeRef.value!.setCheckedKeys([], false)
}
const rowClassName = ({ id }) => {
  return id === currentKey.value ? 'active-node' : ''
}

const props = {
  value: 'name',
  label: 'name',
  children: 'childs',
}

onMounted(() => {
  var tree = document.getElementById("tree");
  tree.addEventListener('contextmenu', function (event) {
    event.preventDefault(); // 取消默认的右键菜单行为
  })

  document.addEventListener('mouseup', function (event) {
    if (event.button === 1 || event.button == 0) { // event.button表示按下的鼠标按钮编号，2表示右键
      var customMenu = document.getElementById("custom-menu");
      if (customMenu) {
        customMenu.style.display = "none";
      }
    }
  });
  ListToolMeau()
})

const toggleExpand = (data,node) => {
  node.expanded = !node.expanded
  handleNodeClick(data,node)
}

const handleNodeClick = async (data, node) => {
  cur_data.value = data
  cur_node.value = node
  if (data.childs == undefined) {
    data.childs = []
  }
  if (data.childs.length != 0) {
    return
  }

  data.childs = await ListToolChild2(data.id)
}


const ListToolMeau = async () => {
  var res = await meau.List()
  await ConCatRes(res)
  tableData.value = res.data
  tableData.value = tableData.value.concat(res.cases)
}

const ConCatRes = async (res) => {
  for (var i in res) {
    res[i].childs = []
    if (res[i].childTools != undefined) {
      if (res[i].childTools.length > 0) {
        res[i].childs = await res[i].childs.concat(res[i].childTools)
      }
    }
    if (res[i].childMeaus != undefined) {
      if (res[i].childMeaus.length > 0) {
        res[i].childs = await res[i].childs.concat(res[i].childMeaus)
      }
    }
  }
  return res
}
const ListToolChild2 = async (id) => { //获取目录的子目录
  var res = await meau.List({"id": id})
  var childs = []
  if (res.data != undefined) {
    if (res.data.length > 0) {
      childs = await childs.concat(res.data)
    }
  }
  if (res.cases != undefined) {
    if (res.cases.length > 0) {
      childs = await childs.concat(res.cases)
    }
  }
  return await childs
}
</script>

<style scoped>
#custom-menu {
  display: none; /* 初始状态下不显示 */
  position: absolute;
  background-color: #f9f9f9;
  font-family: 微软雅黑;
  min-width: 120px;
  border-radius: 10px;
  box-shadow: 3px 3px 4px rgba(0, 0, 0, .2);
  z-index: 9999;
}

#custom-menu ul li {
  padding: 8px 16px;
  cursor: pointer;
  list-style: none;
}

#custom-menu ul li:hover {
  background-color: rgba(194, 191, 191, 0.92);
}
.active-node  {
  color: #d98129;
  font-weight: bold;
}
.testcase {
  color: #3c92e8;
}
</style>